// key为cookie的名称 val为值 time为过期时间 (单位是 秒)
export const setCookie = (key, val, time) => {
    if (typeof key !== 'string' || typeof val !== 'string') {
        return false;
    }
    time = time || 7 * 24 * 3600;
    var exp = new Date();
    exp.setTime(exp.getTime() + time * 1000);
    document.cookie = key + '=' + val + ';expires=' + exp.toUTCString();
}

export const mySetCookie = (cname, cvalue, exdays) => {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

// 获取所有的cookie
export const getAllCookies = () => {
    let cookies = document.cookie.split(/;\s/g);
    let cookieObj = {};
    cookies.forEach(function(item) {
        let key = item.split('=')[0];
        cookieObj[key] = item.split('=')[1];
    });
    return cookieObj;
}

// 通过key 获取cookie
export const getCookieByKey = (key) => {
    return getAllCookies()[key];
}

// 通过key 来删除cookie
export const clearCookieByKey = (key) => {
    setCookie(key, "", -1);
}

// 清空所有的cookies
export const clearAllCookies = () => {
    let keys = Object.keys(getAllCookies());
    keys.forEach(function (item) {
        clearCookieByKey(item);
    });
}

